<?php

/* 分享 */
namespace app\appapi\controller;

use cmf\controller\HomeBaseController;
use think\facade\Db;

class AgentController extends HomebaseController{

	public function index() {
        $data = $this->request->param();
        $uid=(int)checkNull($data['uid']);
        $token=checkNull($data['token']);
        
        $checkToken=checkToken($uid,$token);
		if($checkToken==700){
			$reason=lang('您的登陆状态失效，请重新登陆！');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
		}
        $configpri=getConfigPri();
        if($configpri['agent_switch']!=1){
            $reason=lang('信息错误');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
        }
        
        $code=Db::name('agent_code')->where("uid={$uid}")->value('code');
        if(!$code){
            $code=$this->createCode();
            Db::name('agent_code')->insert(['uid'=>$uid,'code'=>$code]);
        }
        $code_a=str_split($code);
        
        $one_nums=Db::name('agent')
			->where("one={$uid}")
			->count();
			
		$agentinfo=array();
        
        /* 是否是分销下级 */
        $users_agent=Db::name("agent")->where(["uid"=>$uid])->find();
		if($users_agent){
			$agentinfo= getUserInfo($users_agent['one']);
		}

		
        $this->assign('uid', $uid);
        $this->assign('token', $token);
        $this->assign('code', $code);
        $this->assign('code_a', $code_a);
        $this->assign('one_nums', $one_nums);
        $this->assign('agent_one', $configpri['agent_one']);
        $this->assign('agent_reward', $configpri['agent_reward']);
        $this->assign('agentinfo', $agentinfo);
		
		
		$config=getConfigPub();
		$language=cmf_current_lang();	
		if($language=='en'){
			
			$config['name_coin']=$config['name_coin_en'];
			$config['name_votes']=$config['name_votes_en'];
		}
		$this->assign('config',$config);
        

        return $this->fetch();
	}	
	
	
	public function agent(){
		$data = $this->request->param();
        $uid=isset($data['uid']) ? $data['uid']: '';
        $token=isset($data['token']) ? $data['token']: '';
        $uid=(int)checkNull($uid);
        $token=checkNull($token);
        
        $checkToken=checkToken($uid,$token);
		if($checkToken==700){
			$reason=lang('您的登陆状态失效，请重新登陆！');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
		}
		
		$agentinfo=array();
		
		$users_agent=Db::name('agent')->where(["uid"=>$uid])->find();
		if($users_agent){
			$agentinfo=getUserInfo($users_agent['one']);
			
			$code=Db::name('agent_code')->where("uid={$users_agent['one']}")->value('code');
			
			$agentinfo['code']=$code;
			$code_a=str_split($code);

			$this->assign("code_a",$code_a);
		}
	
		
		$this->assign("uid",$uid);
		$this->assign("token",$token);

		$this->assign("agentinfo",$agentinfo);

		return $this->fetch();
	}
	
	public function setAgent(){
		$data = $this->request->param();

        $uid=isset($data['uid']) ? $data['uid']: '';
        $token=isset($data['token']) ? $data['token']: '';
        $code=isset($data['code']) ? $data['code']: '';
        $uid=(int)checkNull($uid);
        $token=checkNull($token);
        $code=checkNull($code);
		
		$rs=array('code'=>0,'info'=>array(),'msg'=>lang('设置成功'));
		
		if(checkToken($uid,$token)==700){
			$rs['code']=700;
			$rs['msg']=lang('您的登陆状态失效，请重新登陆！');
			echo json_encode($rs);
			exit;
		} 

		if($code==""){
			$rs['code']=1001;
			$rs['msg']=lang('邀请码不能为空');
			echo json_encode($rs);
			exit;
		}
		
		$isexist=Db::name('agent')->where(["uid"=>$uid])->find();

		if($isexist){
			$rs['code']=1001;
			$rs['msg']=lang('已设置');
			echo json_encode($rs);
			exit;
		}
		
		//获取邀请码用户
		$oneinfo=Db::name('agent_code')->field("uid")->where(["code"=>$code])->find();

		if(!$oneinfo){
			$rs['code']=1002;
			$rs['msg']=lang('邀请码错误');
			echo json_encode($rs);
			exit;
		}

		//邀请码用户ID
		$code_uid=$oneinfo['uid'];
		
		if($code_uid==$uid){
			$rs['code']=1003;
			$rs['msg']=lang('不能填写自己的邀请码');
			echo json_encode($rs);
			exit;
		}
		
		//获取邀请码用户的上下级关系
		$one_agent=Db::name('agent')->where("uid={$code_uid}")->find();

		if(!$one_agent){
			$one_agent=array(
				'uid'=>$code_uid,
				'one'=>0,
			);
		}else{

			if($one_agent['one']==$uid){
				$rs['code']=1004;
				$rs['msg']=lang('您已经是该用户的上级');
				echo json_encode($rs);
				exit;
			}
		}

		//上级用户ID
		$one_uid=$one_agent['uid'];
		
		$data=array(
			'uid'=>$uid,
			'one'=>$one_uid,
			'addtime'=>time(),
		);
		Db::name('agent')->insert($data);
		
		//邀请奖励
		
		$date = date("Ymd");
        $configpri=getConfigPri();
        $agent_reward=$configpri['agent_reward'];
        $agent_daytimes=$configpri['agent_daytimes'];
        $agent_times=$configpri['agent_times'];
		
		//奖励次数
		$getLimit=Db::name('agent_limit')
			->where("uid={$one_uid}")
			->find();

		if($getLimit){

			if($getLimit['times']>=$agent_times){
				echo json_encode($rs);
				exit;
			}
				
			if( $getLimit['addtime']==$date ){
				/* 当天 */
				if( $agent_daytimes >0 && $getLimit['daytimes']>=$agent_daytimes){
					echo json_encode($rs);
					exit;
				}
				
				Db::name('agent_limit')
						->where("uid={$one_uid}")
						->inc("times",1)->update();
						
				Db::name('agent_limit')
					->where("uid={$one_uid}")
					->inc("daytimes",1)->update();
				
			}else{
				/* 新一天 */
				
				Db::name('agent_limit')
						->where("uid={$one_uid}")
						->inc("times",1)->update();

				Db::name('agent_limit')
						->where("uid={$one_uid}")
						->update(array('daytimes'=>1,'addtime'=>$date));
			}
			
		}else{
			 $da=[
                'uid'=>$one_uid,
                'times'=>1,
                'daytimes'=>1,
                'addtime'=>$date,
            ];
			Db::name('agent_limit')->insert($da);
		}

		if($agent_reward){
			addVotes($one_uid,$agent_reward,$agent_reward);

			//添加映票收入记录
            $data=array(
                'type'=>1,
                'action'=>1, //注册邀请奖励
                'uid'=>$one_uid, //收入用户id
                'fromid'=>$uid, //贡献用户id
                'total'=>$agent_reward,
                'votes'=>$agent_reward,
                'addtime'=>time()
            );

            addVoteRecord($data);

            //上级用户邀请关系收益
            $oneuid_profit=Db::name("agent_profit")
            		->where("uid={$one_uid}")
            		->find();

            if($oneuid_profit){
            	//给上级用户增加作为上级用户的总收益
            	Db::name("agent_profit")
            		->where("uid={$one_uid}")
            		->inc("one_p",$agent_reward)->update();
            }else{
            	Db::name("agent_profit")
            		->insert(['uid'=>$one_uid,'one_p'=>$agent_reward]);
            }

            //本用户邀请关系收益
            $uid_profit=Db::name("agent_profit")
            		->where("uid={$uid}")
            		->find();

            if($uid_profit){
            	Db::name("agent_profit")
            		->where("uid={$uid}")
            		->inc("one",$agent_reward)->update();
            }else{
            	Db::name("agent_profit")
            		->insert(['uid'=>$uid,'one'=>$agent_reward]);
            }
		}

		echo json_encode($rs);
		exit;
	}
    
    public function share() {
        $data = $this->request->param();
        $code=checkNull($data['code']);
        

        $configpri=getConfigPri();
        if($configpri['agent_switch']!=1){
            $reason=lang('信息错误');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
        }
        
        $uid=Db::name('agent_code')->where("code='{$code}'")->value('uid');
        if(!$uid){
            $reason=lang('信息错误');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
        }
        
        $userinfo=getUserInfo($uid);
        $openinstall_switch=$configpri['openinstall_switch'];

        $this->assign('code', $code);
        $this->assign('userinfo', $userinfo);
        $this->assign('openinstall_switch',$openinstall_switch);
        

        return $this->fetch();
	}

    public function one() {
        
        $data = $this->request->param();
        $uid=(int)checkNull($data['uid']);
        $token=checkNull($data['token']);
        
        $checkToken=checkToken($uid,$token);
		if($checkToken==700){
			$reason=lang('您的登陆状态失效，请重新登陆！');
			$this->assign('reason', $reason);
			return $this->fetch(':error');
		}
        

        $map[]=['one','=',$uid];
        
        $list = Db::name('agent')
            ->where($map)
            ->order("addtime desc")
            ->paginate(50);
        
        $list->each(function($v,$k){
            $coin='0';
            $info=Db::name('agent_profit')->where("uid={$v['uid']}")->value('one');
            if($info){
                $coin=$info;
            }
            $v['coin']=$coin;
            
            $userinfo=getUserInfo($v['uid']);
            $v['userinfo']=$userinfo;
           
            $v['addtime']=date('Y.m.d',$v['addtime']);
           
            return $v; 
        });        
       

        $this->assign('list', $list);
        $this->assign('uid', $uid);
        $this->assign('token', $token);
        

        return $this->fetch();
	}
    
	function one_more(){
        $result=array(
			'list'=>[],
			'nums'=>0,
			'isscroll'=>0,
		);
        
        $data = $this->request->param();
        $uid=(int)checkNull($data['uid']);
        $token=checkNull($data['token']);
        
        $checkToken=checkToken($uid,$token);
		if($checkToken==700){
			return $result;
		}
		
		$map[]=['one','=',$uid];
        $pnums=50;
        $list = Db::name('agent')
            ->where($map)
            ->order("addtime desc")
            ->paginate($pnums);
        
        $list->each(function($v,$k){
            $coin='0';
            $info=Db::name('agent_profit')->where("uid={$v['uid']}")->value('one');
            if($info){
                $coin=$info;
            }
            $v['coin']=$coin;
            
            $userinfo=getUserInfo($v['uid']);
            $v['userinfo']=$userinfo;
           
            $v['addtime']=date('Y.m.d',$v['addtime']);
           
            return $v; 
        });
		
        $nums=count($list);
		if($nums<$pnums){
			$isscroll=0;
		}else{
			$isscroll=1;
		}
        
        $result=array(
			'list'=>$list,
			'nums'=>$nums,
			'isscroll'=>$isscroll,
		);

        return $result;
	}

	
	/* 生成邀请码 */
	protected function createCode($len=6,$format='ALL2'){
        $is_abc = $is_numer = 0;
        $password = $tmp =''; 
        switch($format){
            case 'ALL':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
            case 'ALL2':
                $chars='ABCDEFGHJKLMNPQRSTUVWXYZ0123456789';
                break;
            case 'CHAR':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
                break;
            case 'NUMBER':
                $chars='0123456789';
                break;
            default :
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
        }
        
        while(strlen($password)<$len){
            $tmp =substr($chars,(mt_rand()%strlen($chars)),1);
            if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
                $is_numer = 1;
            }
            if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
                $is_abc = 1;
            }
            $password.= $tmp;
        }
        if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
            $password = $this->createCode($len,$format);
        }
        if($password!=''){
            
            $oneinfo=Db::name('agent_code')
	            ->where("code='{$password}'")
	            ->find();
	        
            if(!$oneinfo){
                return $password;
            }            
        }
        $password = $this->createCode($len,$format);
        return $password;
    }

    
    public function downapp(){

		$configpri=getConfigPri();
		$openinstall_appkey=$configpri['openinstall_appkey'];
		$this->assign('openinstall_appkey',$openinstall_appkey);

		return $this->fetch();
	}
}